package com.zx.idc.backend.gui.api.ftp.sftp;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.zx.idc.backend.gui.api.ftp.FtpChannelFactory;
import com.zx.idc.backend.gui.api.ftp.FtpClientConfig;
import com.zx.idc.common.pool.Pool;

import java.lang.reflect.Field;

public class SftpChannelSftpFactory extends FtpChannelFactory<ChannelSftp> {
    public SftpChannelSftpFactory(Pool<Session> sessionPool, FtpClientConfig sftpClientConfig) {
        super(sessionPool, sftpClientConfig);
    }

    @Override
    public ChannelSftp createNew() {
        final Session session = super.sessionPool.get();
        if (session != null && session.isConnected()) {
            try {
                final ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
                sftp.connect();
                //使用反射强制修改编码格式
                Class cl = ChannelSftp.class;
                Field f1 = cl.getDeclaredField("server_version");
                f1.setAccessible(true);
                f1.set(sftp, 2);
                sftp.setFilenameEncoding(ftpClientConfig.getEncoding());

                log.info("Sftp connection successful: {}", sftp);
                return sftp;
            } catch (JSchException | IllegalAccessException | SftpException | NoSuchFieldException e) {
                throw new RuntimeException(e);
            } finally {
                sessionPool.release(session);
            }
        }
        throw new IllegalArgumentException("Sftp session cannot be null!");
    }
}
